<template>
  <!-- 角色页面 -->
  <div>
    <el-card>
    <!-- 模糊查框 添加按钮 -->
    <div class="abvoeBox">
        角色名称:<el-input placeholder="请输入内容" v-model="roleName" class="abvoeBox_input"></el-input>
        <el-button type="primary" @click="selectRoleBackEntity()" style="margin-left:10px">查询</el-button>
        <el-button type="success" @click="openSaveRoleDialogVisible()">添加</el-button>
    </div>
    <!-- 全查数据 -->
    <div class="belowBox">
       <el-table
            :data="tableData"
            border
            >
            <!-- fixed -->
            <el-table-column
            fixed
            prop="roleName"
            label="角色名称">
            </el-table-column>
            <el-table-column
            prop="createTime"
            label="创建时间">
            </el-table-column>
            <el-table-column
            prop="updateTime"
            label="修改时间">
            </el-table-column>
            <el-table-column
            prop="back"
            label="备注">
            </el-table-column>
            <!-- fixed="right" -->
            <el-table-column
            label="操作"
            fixed="right"
            width="300px">
            <template slot-scope="scope">
                <el-button type="info" size="small" @click="selectMenuBackEntity(scope.row)">权限分配</el-button>
                <el-button type="primary" size="small" @click="selectRoleBackEntityByOne(scope.row)">查看</el-button>
                <el-button type="danger" size="small" @click="deleteRoleBackEntityById(scope.row.id)">删除</el-button>
                <el-button type="success" size="small" @click="openUpdateRoleDialogVisible(scope.row)">编辑</el-button>
            </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 20px;">
        <template>
            <div class="block">
                <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="5"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </div>
        </template>
    </div>
    <!-- 单查角色详情 -->
    <el-dialog
        title="详情"
        :visible.sync="selectRoleBackDialogVisible"
        width="40%"
        >
        <el-form :model="tableDataForm" ref="ruleForm" label-width="100px" class="demo-ruleForm" style="text-align: left;">
            <el-form-item label="角色名称">
                <el-input v-text="tableDataForm.roleName" style="width: 200px;"></el-input>
            </el-form-item>
            <!-- <el-form-item label="菜单ids">
                <el-input v-text="tableDataForm.menuIds" style="width: 200px;"></el-input>
            </el-form-item> -->
            <el-form-item label="创建角色时间">
                <el-input v-text="tableDataForm.createTime" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="修改角色时间">
                <el-input v-text="tableDataForm.updateTime" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="备注">
                <el-input v-text="tableDataForm.back" style="width: 200px;"></el-input>
            </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 添加，修改弹窗 -->
    <el-dialog
        :title="title"
        :visible.sync="saveOrUpdateRoleDialogVisible"
        :before-close="closeExpertFormDialog"
        width="40%"
        >
        <!-- 添加弹窗内容 -->
        <el-form :model="tableDataForm" ref="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm" style="text-align: left;">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="tableDataForm.roleName" style="width: 200px;"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="back">
                <el-input v-model="tableDataForm.back" style="width: 200px;"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="resetForm('ruleForm')">取 消</el-button>
            <el-button type="primary" @click="saveOrUpdateRoleBackEntity('ruleForm')">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 分配权限窗口 -->
    <el-dialog title="分配角色权限" :visible.sync="permissionDialogVisible" width="40%">
        <span>
          <el-tree
          :data="menuBackData"
          show-checkbox
          default-expand-all
          check-strictly
          node-key="id"
          ref="menuBackDataByMenuIds"
          :default-checked-keys="meunids"
          :props="props">
          </el-tree>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="assignPermissions()">确 定</el-button>
        </span>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 权限id回显
      menuBackDataByMenuIds: {},
      // 表单规则
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 0, max: 20, message: '角色名称不能为空', trigger: 'blur' }
        ],
        back: [
          { required: true, message: '请输入备注', trigger: 'blur' },
          { min: 0, max: 20, message: '备注不能为空', trigger: 'blur' }
        ]
      },
      // 点击分配菜单 将本条数据的id存放进去
      insermeunIdstoRole: {
        menuIds: '',
        id: ''
      },
      // 树形 子类方法
      props: {
        label: 'menuName',
        children: 'childrenList'
      },
      // 数组 选中的数据 存放到数组里边
      meunids: [],
      // 权限分配数据集
      menuBackData: [],
      // 权限分配弹窗
      permissionDialogVisible: false,
      // 添加，修改弹窗
      saveOrUpdateRoleDialogVisible: false,
      // 添加，修改弹窗时显示的名字
      title: '',
      // 单查数据集，添加数据集，修改数据集
      tableDataForm: {
      },
      // 单查角色弹窗
      selectRoleBackDialogVisible: false,
      // 模糊查询（角色名称）
      roleName: '',
      // 全查角色表数据集
      tableData: [],
      // 分页 （pageSize）一页展示5条数据 （pageNum）当前页
      pageRequest: {
        pageSize: 5,
        pageNum: 1
      },
      // 分页 前往第1页
      currentPage: 1,
      // 分页
      total: 0
    }
  },
  mounted () {
    // 全查角色表（模糊查角色名字）
    this.selectRoleBackEntity()
  },
  methods: {
    // 添加点击X关闭是清空from表单数据
    closeExpertFormDialog (done) {
      this.$refs.ruleForm.resetFields()
      done() // done 用于关闭 Dialog
    },
    // 添加弹窗里的取消按钮 点击取消是清空from表单数据
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.saveOrUpdateRoleDialogVisible = false // 关闭添加，修改弹窗
    },
    // 权限分配
    assignPermissions () {
      const arr = this.$refs.menuBackDataByMenuIds.getCheckedKeys() // 将被选中的节点，返回
      const str = arr.join(',') // 把数组中的所有元素放入一个字符串，用逗号分隔
      this.insermeunIdstoRole.menuIds = str
      this.$axios.post('/eat-service/roleBack/assignPermissions', this.insermeunIdstoRole).then(res => {
        if (res.status === 200) {
          this.myMessage('success', '权限分配成功')
          this.permissionDialogVisible = false // 关闭权限分配窗口
          this.title = ''
          this.$router.go(0) // 强制刷新
        } else {
          this.myMessage('warning', '权限分配失败')
        }
      })
    },
    // 权限分配弹窗
    selectMenuBackEntity (data) {
      this.$axios.get('/eat-service/menuBack/selectMenuBackEntity').then(res => {
        this.menuBackData = res.data.obj
      }).catch(_err => {
        this.myMessage('error', '查询失败')
      })
      this.insermeunIdstoRole.id = data.id // 将本列获取的id值，存放在insermeunIdstoRole.id中
      this.permissionDialogVisible = true // 打开权限分配弹窗
      this.menuBackDataByMenuIds = JSON.parse(JSON.stringify(data))
      if (this.menuBackDataByMenuIds.menuIds != null) {
        // 将menuBackDataByMenuIds.menuIds的逗号进行分隔，放在meunids数组中
        this.meunids = this.menuBackDataByMenuIds.menuIds.split(',')
      }
    },
    // 删除角色
    deleteRoleBackEntityById (data) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete('/eat-service/roleBack/deleteRoleBackEntityById',
          {
            params: {
              id: data
            }
          }).then(res => {
          if (res.status === 200) {
            this.myMessage('success', '删除成功')
            this.selectRoleBackEntity()
          } else {
            this.myMessage('warning', '删除失败')
          }
        }).catch(res => {
          this.myMessage('erroe', '删除失败，请联系管理员')
        })
      }).catch(() => {
        this.myMessage('info', '已取消删除')
      })
    },
    // 添加，修改角色
    saveOrUpdateRoleBackEntity (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formData = new FormData()
          for (const key in this.tableDataForm) {
            formData.set(key, this.tableDataForm[key])
          }
          this.$axios.post('/eat-service/roleBack/saveOrUpdateRoleBackEntity', formData
          ).then(res => {
            if (res.status === 200) {
              this.myMessage('success', '恭喜你，操作成功！') // 成功提示
              this.saveOrUpdateRoleDialogVisible = false // 关闭窗口
              this.tableDataForm = {
              }
              this.selectRoleBackEntity()
            } else {
              this.myMessage('warning', res.data.obj) // 提示消息
            }
          }).catch(error => {
            console.log(error)
            this.myMessage('warning', '对不起，保存失败！')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 打开修改弹窗
    openUpdateRoleDialogVisible (data) {
      this.title = '修改'
      this.saveOrUpdateRoleDialogVisible = true // 打开修改弹窗
      this.tableDataForm = JSON.parse(JSON.stringify(data))
    },
    // 打开添加弹窗
    openSaveRoleDialogVisible () {
      this.title = '添加'
      this.saveOrUpdateRoleDialogVisible = true // 打开添加弹窗
      this.tableDataForm = {
        id: 0
      }
    },
    // 单查角色详情
    selectRoleBackEntityByOne (data) {
      this.selectRoleBackDialogVisible = true
      this.tableDataForm = data
    },
    // 全查角色表（模糊查角色名字）
    selectRoleBackEntity () {
      this.$axios.get('/eat-service/roleBack/selectRoleBackEntity',
        {
          params: {
            roleName: this.roleName,
            pageSize: this.pageRequest.pageSize,
            pageNum: this.pageRequest.pageNum
          }
        }
      ).then(res => {
        this.tableData = res.data.content
        this.total = res.data.total
      }).catch(error => {
        console.log(error)
      })
    },
    // 分页 每页条数
    handleSizeChange (val) {
      this.pageRequest.pageSize = val
      this.selectRoleBackEntity()
    },
    // 分页 当前页
    handleCurrentChange (val) {
      this.pageRequest.pageNum = val
      this.selectRoleBackEntity()
    },
    // 弹窗提示
    myMessage (type, message) {
      this.$message({
        type: type,
        message: message
      })
    }
  }
}
</script>

<style>
    .abvoeBox{
        width: 100%;
        height: 60px;
        text-align: left;
        margin-top: 5px;
        /* background-color: royalblue; */
        /* position: relative; */
    }
    .abvoeBox_input{
        width: 200px;
        height: 50px;
        margin-left: 10px;
        /* position: absolute; */
    }
    .belowBox{
        margin-top: 20px;
    }
</style>
